
const mfs = require('./mfs');

function replaceAutoConfig(config) {
    
    const autoConfig =
        `export class AutoConfig{
    public static readonly hotVersionRelease: string = "${config.hotVersion}";
    public static readonly hotVersionDebug: string = "${config.hotVersionDebug}";
}`

    mfs.writeFile(mfs.join(config.AutoConfigPath, 'AutoConfig.ts'), autoConfig);
    console.log("===replace AutoConfig.ts=====")
    console.log(autoConfig);
}

module.exports.replaceAutoConfig = replaceAutoConfig;


function replaceAndroidManifest(config) {
    let data =
        `<?xml version="1.0" encoding="utf-8"?>
        <manifest xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:tools="http://schemas.android.com/tools"
            package="${config.packageName}"
            android:installLocation="auto">
        
            <uses-feature android:glEsVersion="0x00020000" />
            <uses-permission android:name="android.permission.READ_PRIVILEGED_PHONE_STATE" tools:ignore="ProtectedPermissions"/>
            <!--小米、广点通、穿山甲-->
            <uses-permission android:name="android.permission.INTERNET"/>
            <!--小米、广点通、穿山甲-->
            <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
            <!--小米、广点通、穿山甲-->
            <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
            <!--小米、广点通、穿山甲-->
            <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
            <!--小米、广点通、穿山甲-->
            <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
            <!--广点通、穿山甲-->
            <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
            <!--小米、穿山甲-->
            <uses-permission android:name="android.permission.GET_TASKS"/>
            <!--广点通、穿山甲 非必须-->
            <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
            <!--穿山甲 如果有视频相关的广告且使用textureView播放，请务必添加，否则黑屏-->
            <uses-permission android:name="android.permission.WAKE_LOCK" />
            <!--广点通、穿山甲 targetSdkVersion >= 26 时需要配置此权限，否则无法进行安装app的动作-->
            <uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES"/>
            <!--小米-->
            <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
            <!--小米-->
            <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
            <!--小米-->
            <uses-permission android:name="android.permission.SEND_DOWNLOAD_COMPLETED_INTENTS"/>
            <!--小米-->
            <uses-permission android:name="android.permission.DOWNLOAD_WITHOUT_NOTIFICATION" /><!--1.3.1-releases 新增，获取应用最近使用记录-->
            <uses-permission android:name="android.permission.PACKAGE_USAGE_STATS" tools:ignore="ProtectedPermissions" /><!--1.6.2-releases 新增--><uses-permission android:name="android.permission.AUTHENTICATE_ACCOUNTS" />
            <uses-permission android:name="android.permission.GET_ACCOUNTS" />
            <uses-permission android:name="android.permission.WRITE_SYNC_SETTINGS" />
            <uses-permission android:name="android.permission.READ_SYNC_STATS"/>
        
            <application
                android:name="com.yunhoon.framework.app.MainApplication"
                android:allowBackup="true"
                android:label="@string/app_name"
                android:usesCleartextTraffic="true"
                android:requestLegacyExternalStorage="true"
                android:theme="@style/MyAppThemeTrans"
                android:icon="@mipmap/ic_launcher">
                <!-- Tell Cocos2dxActivity the name of our .so -->
                <meta-data android:name="android.app.lib_name"
                           android:value="cocos2djs" />
        
        
                <activity
                    android:name="org.cocos2dx.javascript.AppActivity"
                    android:screenOrientation="portrait"
                    android:configChanges="orientation|keyboardHidden|screenSize|screenLayout"
                    android:label="@string/app_name"
                    android:theme="@style/MyAppThemeTrans"
                    android:launchMode="singleTop">
                    <intent-filter>
                        <action android:name="android.intent.action.MAIN" />
                        <category android:name="android.intent.category.LAUNCHER" />
                    </intent-filter>
                    <!--要想在别的App上能成功调起App，必须添加intent过滤器-->
                    <intent-filter>
                        <!--协议部分，随便设置-->
                        <data
                            android:host="${config.title}"
                            android:path="/"
                            android:port="80"
                            android:scheme="${config.scheme}"/>
                        <!--下面这几行也必须得设置scheme-->
                        <category android:name="android.intent.category.DEFAULT"/>
                        <action android:name="android.intent.action.VIEW"/>
                        <category android:name="android.intent.category.BROWSABLE"/>
                    </intent-filter>
                </activity>
                <activity
                    android:name="${config.packageName}.wxapi.WXEntryActivity"
                    android:label="@string/app_name"
                    android:exported="true"
                    android:launchMode="singleTask"
                    android:theme="@android:style/Theme.Translucent.NoTitleBar" />
                <provider
                    android:name="${config.packageName}.AppFileProvider"
                    android:authorities="${config.packageName}.AppFileProvider"
                    android:exported="false"
                    android:grantUriPermissions="true">
                    <meta-data
                        android:name="android.support.FILE_PROVIDER_PATHS"
                        android:resource="@xml/yh_fileprovider_paths" />
                </provider>
            </application>
        </manifest>        
`

    let path = config.nativePath + "/frameworks/runtime-src/proj.android-studio/app"
    mfs.writeFile(mfs.join(path, 'AndroidManifest.xml'), data);
    console.log("===replace game AndroidManifest.xml=====")
    console.log(data);
}

module.exports.replaceAndroidManifest = replaceAndroidManifest;
function replaceBuildGradle(config) {
    let android_config = config.android_config;
    let buildDir = "${buildDir}"
    let variantDirName = "${variant.dirName}"
    let sourceDir = "${sourceDir}"
    let outputDir = "${outputDir}"
    let data =
        `import org.apache.tools.ant.taskdefs.condition.Os

        apply plugin: 'com.android.application'
        
        android {
            compileSdkVersion ${android_config.compileSdkVersion}
            buildToolsVersion '${android_config.buildToolsVersion}'
        
            packagingOptions {
                exclude 'META-INF/proguard/okhttp3.pro'
            }

            //打包后应用名称
            android.applicationVariants.all { variant ->
                variant.outputs.all { output ->
                    variant.getPackageApplication().outputDirectory = new File("../../../../../apks/"+buildType.name)
                    def outputFile = output.outputFile
                    if (outputFile != null && outputFile.name.endsWith('.apk')) {
                        //这里修改apk文件名
                        outputFileName = "${config.title}" + "_joyo_v" +
                                "_" + defaultConfig.versionName + "_" +
                                new Date().format("yyyyMMddHHmm") + "_" + buildType.name +
                                ".apk"
                    }
                }
            }
        
            defaultConfig {
                applicationId "${config.packageName}"
                minSdkVersion PROP_MIN_SDK_VERSION
                targetSdkVersion PROP_TARGET_SDK_VERSION
                versionCode ${android_config.versionCode}
                versionName "${android_config.versionName}"
        
                dexOptions {
                    incremental true
                    javaMaxHeapSize "4g"
                }
        
                ndk{
                    abiFilters "armeabi-v7a"
                }
        
                externalNativeBuild {
                    ndkBuild {
                        if (!project.hasProperty("PROP_NDK_MODE") || PROP_NDK_MODE.compareTo('none') != 0) {
                            // skip the NDK Build step if PROP_NDK_MODE is none
                            targets 'cocos2djs'
                            arguments 'NDK_TOOLCHAIN_VERSION=clang'
                            
                            def module_paths = [project.file("../../../cocos2d-x"),
                                                project.file("../../../cocos2d-x/cocos"),
                                                project.file("../../../cocos2d-x/external")]
                            if (Os.isFamily(Os.FAMILY_WINDOWS)) {
                                arguments 'NDK_MODULE_PATH=' + module_paths.join(";")
                            }
                            else {
                                arguments 'NDK_MODULE_PATH=' + module_paths.join(':')
                            }
        
                            arguments '-j' + Runtime.runtime.availableProcessors()
                            abiFilters.addAll(PROP_APP_ABI.split(':').collect{it as String})
                        }
                    }
                }
        
                javaCompileOptions {
                    annotationProcessorOptions {
                        includeCompileClasspath true
                        arguments = [moduleName : project.getName()]
                    }
                }
                //集成新版头条广告上报需添加以下代码
                manifestPlaceholders = [
                        APPLOG_SCHEME  : ""
                ]
            }
        
            sourceSets.main {
                java.srcDirs "../src", "src"
                res.srcDirs "../res", 'res'
                jniLibs.srcDirs "../libs", 'libs'
                manifest.srcFile "AndroidManifest.xml"
            }
        
            externalNativeBuild {
                ndkBuild {
                    if (!project.hasProperty("PROP_NDK_MODE") || PROP_NDK_MODE.compareTo('none') != 0) {
                        // skip the NDK Build step if PROP_NDK_MODE is none
                        path "jni/Android.mk"
                    }
                }
            }
        
            signingConfigs {
        
               release {
                    if (project.hasProperty("RELEASE_STORE_FILE")) {
                        storeFile file(RELEASE_STORE_FILE)
                        storePassword RELEASE_STORE_PASSWORD
                        keyAlias RELEASE_KEY_ALIAS
                        keyPassword RELEASE_KEY_PASSWORD
                    }
                   v2SigningEnabled false
                }
            }
        
            buildTypes {
                release {
                    debuggable false
                    jniDebuggable false
                    renderscriptDebuggable false
                    minifyEnabled true
                    shrinkResources true
                    proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
                    if (project.hasProperty("RELEASE_STORE_FILE")) {
                        signingConfig signingConfigs.release
                    }
        
                    externalNativeBuild {
                        ndkBuild {
                            arguments 'NDK_DEBUG=0'
                        }
                    }
                }
        
                debug {
                    debuggable true
                    jniDebuggable true
                    renderscriptDebuggable true
                    if (project.hasProperty("RELEASE_STORE_FILE")) {
                        signingConfig signingConfigs.release
                    }
                    externalNativeBuild {
                        ndkBuild {
                            arguments 'NDK_DEBUG=1'
                        }
                    }
                }
            }
            //如果你的module 中使用了 Java1.8，那你必须也要添加如下代码到你的app gradle 中
            compileOptions {
                sourceCompatibility JavaVersion.VERSION_1_8
                targetCompatibility JavaVersion.VERSION_1_8
            }
        }
        
        android.applicationVariants.all { variant ->
            // delete previous files first
            delete "${buildDir}/intermediates/merged_assets/${variantDirName}"
        
            variant.mergeAssets.doLast {
                def sourceDir = "${buildDir}/../../../../.."
        
                copy {
                    from "${sourceDir}/assets"
                    into "${outputDir}/assets"
                }
        
                copy {
                    from "${sourceDir}/src"
                    into "${outputDir}/src"
                }
        
                copy {
                    from "${sourceDir}/jsb-adapter"
                    into "${outputDir}/jsb-adapter"
                }
        
                copy {
                    from "${sourceDir}/main.js"
                    from "${sourceDir}/project.json"
                    into outputDir
                }
            }
        }
        
        dependencies {
            implementation fileTree(dir: '../libs', include: ['*.jar','*.aar'])
            implementation fileTree(dir: 'libs', include: ['*.jar','*.aar'])
            implementation fileTree(dir: "../../../cocos2d-x/cocos/platform/android/java/libs", include: ['*.jar'])
            implementation project(':libcocos2dx')
        
            implementation 'androidx.appcompat:appcompat:1.2.0'
            implementation 'androidx.constraintlayout:constraintlayout:2.0.2'
            def sdkVersionName = "2.0.1.5-releases"
            // sdk主core
            implementation "com.xmiles.platform:platform-core:$sdkVersionName"
            // sdk场景support包
            implementation "com.xmiles.platform:platform-functions:$sdkVersionName"
            // 以下是各第三方广告源，根据需要引入
            // 穿山甲
            implementation "com.xmiles.platform:platform-ad-csj:2.0.1-releases"
            // 广点通
            implementation "com.xmiles.platform:platform-ad-gdt:2.0.1-releases"
            // 快手
            implementation "com.xmiles.platform:platform-ad-kuaishou:2.0.1-releases"
        
            //权限
            implementation 'com.github.tbruyelle:rxpermissions:0.12'
        
            //其中latest.release指代最新Bugly SDK版本号，也可以指定明确的版本号，例如2.2.0
            implementation 'com.tencent.bugly:crashreport:3.3.9'
        
            // 友盟统计SDK
            implementation  'com.umeng.umsdk:common:9.4.0' // 必选
            implementation  'com.umeng.umsdk:asms:1.2.3' // 必选

            //下载apk相关
            implementation 'com.squareup.retrofit2:retrofit:2.5.0'//Retrofit依赖
            implementation 'com.squareup.retrofit2:adapter-rxjava2:2.5.0'
            implementation 'io.reactivex.rxjava2:rxandroid:2.1.0'
        }        
`


    let path = config.nativePath + "/frameworks/runtime-src/proj.android-studio/app"
    mfs.writeFile(mfs.join(path, 'build.gradle'), data);
    console.log("===replace game build.gradle=====")
    console.log(data);
}

module.exports.replaceBuildGradle = replaceBuildGradle;

function replaceGameConst(config) {
    let android_config = config.android_config;
    let data =
        `package com.yunhoon.framework.publicdata;

        public class GameConfig {
            //微信appid
            public static final String WX_APPID = "${android_config.WX_APPID}";
            public static final String WX_APPSECRET = "${android_config.WX_APPSECRET}";
            //邀请码前缀
            public static final String INVITE_CODE_PREFIX = "${android_config.INVITE_CODE_PREFIX}";
            //buglyid
            public static final String BUGLY_ID = "${android_config.BUGLY_ID}";
            //友盟ID
            public static final String UMENG_ID = "${android_config.UMENG_ID}";
            //TalkingData Id
            public static final String TALKING_DATA_ID = "${android_config.TALKING_DATA_ID}";
            //产品ID
            public static final String PRODUCT_ID = "${android_config.PRODUCT_ID}";
            // 正式
            public static final String APP_TT = "${android_config.APP_TT}";
            public static final String APP_GDT= "${android_config.APP_GDT}";
            public static final String APP_KUAI_SHOU= "${android_config.APP_KUAISHOU}";
            //开屏
            public static final String POS_SPLASH = "${android_config.POS_SPLASH}";
            //弹窗
            public static final String POS_IMAGE_POP = "${android_config.POS_IMAGE_PAGE}";
            //公用的
            public static final String POS_PUBLIC_VIDEO = "${android_config.POS_VIDEO}";
            //banner广告
            public static final String POS_BANNER = "${android_config.POS_BANNER}";
            //插屏广告
            public static final String POS_POP = "${android_config.POS_POP}";
            //第三方广告ID
            public static final String OTHER_AD_APP_ID = "${android_config.OTHER_AD_APP_ID}";
            //第三方广告视频ID
            public static final String OTHER_AD_VIDEO_ID = "${android_config.OTHER_AD_VIDEO_ID}";
        }                
`

    let path = config.nativePath + "/frameworks/runtime-src/proj.android-studio/app/src/com/yunhoon/framework/publicdata"
    mfs.writeFile(mfs.join(path, 'GameConfig.java'), data);
    console.log("===replace GameConfig.java=====")
    console.log(data);
}

module.exports.replaceGameConst = replaceGameConst;